import {Component, OnInit, EventEmitter, Directive} from '@angular/core';
import {CONSTANT} from "../../service/constant.service";
import {TitleCpt} from "../../lib/title/title.component";
import {LocalStorage} from "../../app.local-storage";
import {UserModel} from "../../model/user.model";
import {ROUTE} from "../../service/route.service";
import {ActivatedRoute} from "@angular/router";
import {PAYTYPE} from "../../utils/util.utils";
import {FormGroup, FormBuilder, FormControl, Validators, FormArray} from "@angular/forms";
import {nameValidator, peopleIdValidator} from "../../utils/validator.utils";
import {CONTRACT} from "../../service/contract.service";
import {selectDate} from "../../lib/datepicker/datepicker.component";
import {WfToast} from "../../utils/toast.utils";
import {USER} from "../../service/user.service";
declare var $:any;

@Component({
  selector: 'app-place-order-view',
  templateUrl: './place-order-view.component.html',
  styleUrls: ['./place-order-view.component.scss']
})
export class PlaceOrderViewComponent implements OnInit {
  user:UserModel;
  placeOrderTitleCptList:Array<TitleCpt> = this.constant.genPlaceOrderTitleCptList();
  leaseTimeItems:any = this.constant.leaseTimeItems;
  progressBarList:any = this.constant.progressBarList;
  payType:any = '';
  houseId:any;
  payTypeList:any;
  priceInfo:any;
  defaultDate:selectDate = new selectDate('');
  currentPayTypeValue:any;
  currentLeaseId:any;
  orderForm:FormGroup;

  constructor(private constant:CONSTANT,
              private localStorage:LocalStorage,
              private route:ROUTE,
              private routeInfo:ActivatedRoute,
              private paytype:PAYTYPE,
              private formbuilder:FormBuilder,
              private contractApi:CONTRACT,
              private toast:WfToast,
              private USER:USER) {

    this.orderForm = formbuilder.group({
      payType: [''],
      leaseTime: [''],
      startDate: [''],
      lesseeName: ['', nameValidator],
      lesseePeopleId: ['', peopleIdValidator],
      cotenants: formbuilder.array([
        formbuilder.group({
          customerName: ['', nameValidator],
          customerCard: ['', peopleIdValidator]
        })
      ])
    });
    // console.log((this.orderForm.get('cotenants') as FormArray).controls[0]);
    // console.log(this.orderForm.controls)
  }

  setUserInfo() {
    if (this.user) {
      let name:any = this.user.name;
      let idcard:any = this.user.idcard;
      let cotenants = (this.orderForm.get('cotenants')as FormArray).controls[0];
      this.orderForm.get('lesseeName').setValue(name);
      this.orderForm.get('lesseePeopleId').setValue(idcard);
      cotenants.get('customerName').setValue(name);
      cotenants.get('customerCard').setValue(idcard);
    } else {
      let cotenants = (this.orderForm.get('cotenants')as FormArray).controls[0];
      this.orderForm.get('lesseeName').setValue('');
      this.orderForm.get('lesseePeopleId').setValue('');
      cotenants.get('customerName').setValue('');
      cotenants.get('customerCard').setValue('');
    }
  }

  getPayTypeList() {
    let list = this.paytype.transferPayTypeList(parseInt(this.payType));
    let data = {value: '', name: '请选择付款方式'};
    list.unshift(data);
    this.payTypeList = list;
    this.currentPayTypeValue = this.payTypeList[0].value;
  }
  calcPrice(){
    let reqData = {
      houseId: this.houseId,
      lease: this.orderForm.get('leaseTime').value,
      payWay: this.orderForm.get('payType').value,
      leaseStart: this.defaultDate.date
    }
    this.contractApi.calc(reqData,v=>{
      this.priceInfo = v;
    })
  }

  setLeaseTime(type:any, id:any) {
    let _this = this;
    id && id == '1' ? (function () {
      _this.leaseTimeItems.forEach(function (v:any) {
        if (v.value == 1) return v.isdisabled = true;
      });
      _this.currentLeaseId = _this.leaseTimeItems[0].value;
    })() : (function () {
      _this.leaseTimeItems.forEach(function (v:any) {
        return v.isdisabled && delete v.isdisabled;
      });
      _this.currentLeaseId = _this.leaseTimeItems[0].value;
    })();

  }


  goToContractView() {
    let cotenantList = (this.orderForm.get('cotenants') as FormArray).getRawValue();
    let formData = {
      houseId: this.houseId,
      payWay: this.orderForm.get('payType').value,
      lease: this.orderForm.get('leaseTime').value,
      leaseStart: this.defaultDate.date,
      customerName: this.orderForm.get('lesseeName').value,
      customerCard: this.orderForm.get('lesseePeopleId').value,
      customerPhone: this.user.username,
      sex: this.user.sex,
      cotenant: cotenantList
    }
    if (this.orderForm.get('payType').value == '') {
      this.toast.msg('请选择付款方式');
      return;
    }
    if (this.orderForm.get('leaseTime').value == '') {
      this.toast.msg('请选择租期');
      return;
    }
    this.toast.msg('提交成功，开始签约！');
    this.localStorage.setObject('wordFormData', formData);
    this.route.goContractView()
    // this.contractApi.loadContract(formData, (res:any)=> {
    //   this.localStorage.setObject('contract', res);
    //   // console.log(res);
    //   res && res.contractId && this.route.goContractView(res.contractId);
    // })
  }

  getDate(event:selectDate) {
    this.defaultDate = event;
  }

  getcurrentDate(dateTime:any) {
    let now = !!dateTime ? new Date(dateTime) : new Date();
    let date:any = now.getDate();
    let moth:any = now.getMonth() + 1;
    let year:any = now.getFullYear();
    if (date >= 0 && date <= 9) {
      date = "0" + date;
    }
    if (moth >= 0 && moth <= 9) {
      moth = "0" + moth;
    }
    let str = year + '-' + moth + '-' + date;
    return str;
  }

  addConenant() {
    let cotenant = this.orderForm.get('cotenants') as FormArray;
    cotenant.push(this.formbuilder.group({
      customerName: ['', nameValidator],
      customerCard: ['', peopleIdValidator]
    }));
  }

  removeConenant(i:any) {
    let cotenants = this.orderForm.get('cotenants') as FormArray;
    cotenants.removeAt(i);
  }

  ngOnInit() {
    this.user = this.USER.get();
    this.routeInfo.params.subscribe((param:any) => {
      this.houseId = param.id;
      this.payType = param.payType;
    });
    this.getPayTypeList();
    this.currentLeaseId = this.leaseTimeItems[0].value;
    this.setUserInfo();
  }
}
